#!/usr/bin/env python

"""
"""
__author__ = 'rx.wen218@gmail.com'

from post import Post
from datetime import datetime
import htmlutil

class PostConverter:
    """
    Convert posts between different representations:
        1. generic post object (user defined class)
        2. atom entry object (dictionary)
        3. atom entry string
        4. gdata entry object
    """
    def __init__(self):
        pass

    def GetGenericPost(self, post):
        raise NotImplementedError("GetGenericPost isn't implemented in base class")

    def GetSpecificPost(self, post):
        raise NotImplementedError("GetSiteSpecificPost isn't implemented in base class")

class MetaWeblogPostConverter(PostConverter):
    def __init__(self):
        pass

    def GetGenericPost(self, post):
        generic_post = Post(
            postid = post['postid'],
            title = htmlutil.DecodeHtml(post['title']), 
            summary = post['description'], 
            content = post['description'], 
            create_date = post['dateCreated'],
            tags = post.get('categories', []))
        return generic_post

    def GetSpecificPost(self, post):
        specific_post = {}
        specific_post['title'] = post.title
        specific_post['description'] = post.content
        specific_post['dateCreated'] = post.create_date
        specific_post['categories'] = post.tags
        return specific_post

class BloggerPostConverter(PostConverter):
    def __init__(self):
        pass

    def GetGenericPost(self, post):
        generic_post = Post(
            postid = post.id.text,
            title = post.title.text, 
            summary = post.content.text, 
            content = post.content.text, 
            create_date = datetime.strptime(post.published.text[:-6], '%Y-%m-%dT%H:%M:%S.%f'), 
            tags = [category.term for category in post.category])
        return generic_post

    def GetSpecificPost(self, post):
        import gdata
        import atom
        specific_post = BloggerPostConverter.gdata.GDataEntry()
        specific_post.title = BloggerPostConverter.atom.Title(title_type='xhtml', text = post.title)
        specific_post.content = BloggerPostConverter.atom.Content(content_type='html', text = post.content)
        specific_post.published = BloggerPostConverter.atom.Published(text=post.create_date.strftime('%Y-%m-%dT%H:%M:%S.%f'))
        specific_post.category = [BloggerPostConverter.atom.Category(term=category, scheme = 'http://www.blogger.com/atom/ns#') for category in post.tags]
        return specific_post
 
